cflag = 2
loading = $ 'div.loading'

$ document
	.ready ()->
		getCourse()
		$ '.quikCheck'
			.bind 'click',()->
				cflag = 0
				check()
		$ 'button#sure'
			.bind 'click',()->
				if cflag is 0
					signup()
				else if cflag is 1
					addCourse()
		$ 'button#reset'
			.bind 'click',()->
				$ 'input[name=key]'
					.val("")
		$ 'li.add-course'
			.bind 'click',()->
				cflag = 1
				check()
		$ 'button.cancle'
			.bind 'click',()->
				closeCheck()

$ document
	.keydown (event)->
		if event.keyCode is 27
			closeCheck()
		else if event.keyCode is 13
			if cflag is 0
				signup()
			else if cflag is 1
				addCourse()

check = ()->
	if cflag is 0
		$ '.log'
			.html '请输入老师发放的激活码:'
	else
		$ '.log'
			.html '请输入课程号'
	$ '.mask'
		.css 'display','block'

addCourse = ()->
	newCid = $ "input[name=key]"
		.val()
	$.post '/student/addCourse/','cid':newCid,(data)->
		if data.head is 'ok'
			$ ".log"
				.text "选课成功"
			getCourse()
		else
			$ ".log"
				.text data.info

closeCheck = ()->
	$ '.mask'
		.css 'display','none'
	cflag = 2

signup = ()->
	key = $('input[name=key]').val()
	if key? && checkKey key
		$.post '/student/confirm/','key':key,(data1)->
			if data1.head is 'ok'
				conf = window.confirm student.sname + ' 确定签到课程 ' + data1.info.cname + ' 的第 ' + data1.info.times + ' 次签到？'
				if conf
					$.post '/student/signup/','key':key,(data2)->
						if data2.head is 'ok'
							$('div.log').text("签到成功！")
							closeCheck()
						else
							$('div.log').text(data2.info)
				else
					closeCheck()
			else
				$('div.log').text(data1.info)
	else
		$('div.log').text("请输入正确的激活码")

checkKey = (key)->
	if key != ''
		true
	else
		false

getCourse = ()->
	loading.css 'display','block'
	$ '.attention'
		.text ""
	cbody = $ "ul.courses"
	$ "li"
		.remove ".course"
	$.get '/student/getCourse',(data)->
		if data.head is 'ok'
			if data.info isnt 0
				for c in data.info
					li = $ "<li id='#{c.course._id}' class='course' ></li>"
					li.html "<a href='/student/course/#{c.course._id}'><span class='title'>#{c.course.cname}</span></a>"
					cbody.prepend li
				$.get '/student/unbinding',(data2)->
					if data2.head is "ok"
						if data2.info isnt 0
							$ '.attention'
								.text "注意：你有#{data2.info}张老师未绑定的激活码，请等待老师绑定"
		else
			li = $ "<li class='course'>#{data.info}</li>"
			cbody.append li
		loading.css 'display','none'




